package com.kll.carolinehmibiz.presentation.presenter

import android.content.Context
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.base.utils.L
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.net.bean.GetUserInfoResponse
import com.kll.carolinehmibiz.net.bean.UploadFileResponse
import com.kll.carolinehmibiz.presentation.BasePresenter
import com.kll.carolinehmibiz.presentation.listener.MainUcenterProtocol
import java.io.File

class MainUcenterPresenter(context: Context, mView: MainUcenterProtocol.IView): BasePresenter(context), MainUcenterProtocol.IPresenter {
    private var mView: MainUcenterProtocol.IView? = mView
    private var getUserIsBusying = false
    private var editUserInfoIsBusying = false
    private var uploadHeadImgIsBusying = false

    override fun getUser() {
        if (getUserIsBusying) return
        getUserIsBusying = true
        OperationManager.getInstancce().getUserInfo(object : OperateListener {
            override fun onSuccess(state: Int, obj: Any?) {
                getUserIsBusying = false
                if (state == 200) {
                    mView?.getUserInfoSuccessed(obj as GetUserInfoResponse)
                }
            }

            override fun onFail(code: Int, message: String) {
                getUserIsBusying = false
                mView?.getUserInfoFailed(code, message)
            }

        })
    }

    override fun editUserInfo(userInfo: GetUserInfoResponse) {
        if (editUserInfoIsBusying) return
        editUserInfoIsBusying = true
        OperationManager.getInstancce().editUserInfo(userInfo, object : OperateListener {
            override fun onSuccess(state: Int, obj: Any?) {
                editUserInfoIsBusying = false
                if (state == 200) {
                    mView?.editUserInfoSuccessed()
                }
            }

            override fun onFail(code: Int, message: String) {
                editUserInfoIsBusying = false
                mView?.editUserInfoFailed(code, message)
            }

        })
    }

    override fun uploadHeadImg(file: File) {
        if (uploadHeadImgIsBusying) return
        uploadHeadImgIsBusying = true
        OperationManager.getInstancce().uploadHeadImg(file, object : OperateListener {
            override fun onSuccess(state: Int, obj: Any?) {
                uploadHeadImgIsBusying = false
                if (state == 200) {
                    val data = obj as ArrayList<UploadFileResponse>
                    if (data.size == 1) {
                        mView?.uploadHeadImgSuccessed(data[0].url)
                        L.d("TAG", "onSuccess: ${data[0].url}")
                    }
                }
            }

            override fun onFail(code: Int, message: String) {
                uploadHeadImgIsBusying = false
                mView?.uploadHeadImgFailed(code, message)
            }

        })
    }

}